/*
 * Copyright (C) 2016  Nicola Spanti (RyDroid) <dev@nicola-spanti.info>
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 * 
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */


#include "PlanetWars2dRT-core/specific/model/player.h"
#include "PlanetWars2dRT-core/utils/cstring_functions.h"


EXTERN_C_BEGIN


void
player_init_first_time_only(player_t* a_player)
{
  a_player->name      = NULL;
  a_player->data      = NULL;
  a_player->data_free = NULL;
  a_player->act       = NULL;
}

const char*
player_get_name(const player_t* a_player)
{
  return a_player->name;
}

bool
player_set_name(player_t* a_player, const char* new_name)
{
  if(new_name == NULL)
    {
      return false;
    }
  
  char* new_name_copy = get_strcpy(new_name);
  cstring_trim(new_name_copy, ' ');
  cstring_trim(new_name_copy, '\t');
  cstring_trim_new_line(new_name_copy);
  if(cstring_contains(new_name_copy, '\n') ||
     cstring_contains(new_name_copy, '\r'))
    {
      free(new_name_copy);
      return false;
    }
  size_t length = strlen(new_name_copy);
  if(length == 0 ||
     length > PLAYER_NAME_LENGTH_MAX)
    {
      free(new_name_copy);
      return false;
    }
  
  a_player->name = new_name_copy;
  return true;
}

void
player_act_unsafe(player_t* a_player, struct game_t* a_game)
{
  a_player->act(a_game, a_player);
}

void
player_act(player_t* a_player, struct game_t* a_game)
{
  if(a_player != NULL && a_player->act != NULL)
    {
      player_act_unsafe(a_player, a_game);
    }
}

void
player_destructor(player_t* a_player)
{
  if(a_player != NULL)
    {
      if(a_player->name != NULL)
	{
	  free(a_player->name);
	}
      
      if(a_player->data != NULL)
	{
	  if(a_player->data_free == NULL)
	    {
	      free(a_player->data);
	    }
	  else
	    {
	      a_player->data_free(a_player->data);
	    }
	}
    }
}


EXTERN_C_END
